# worker.py
from PyQt5.QtCore import QRunnable, QObject, pyqtSignal
import yt_dlp

class WorkerSignals(QObject):
    progress = pyqtSignal(dict)
    finished = pyqtSignal(bool)

class DownloadTaskWorker(QRunnable):
    def __init__(self, task_id, url, save_dir):
        super().__init__()
        self.task_id = task_id
        self.url = url
        self.save_dir = save_dir
        self.signals = WorkerSignals()

    def run(self):
        ydl_opts = {
            'outtmpl': f'{self.save_dir}/%(title)s.%(ext)s',
            'noplaylist': True,
            'progress_hooks': [self.hook],
            'writesubtitles': True,
            'writeautomaticsub': True,
            'subtitleslangs': ['zh', 'en'],
            'quiet': True,
            'no_warnings': True,
            'format': 'bestvideo+bestaudio/best'
        }

        try:
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                ydl.download([self.url])
            self.signals.finished.emit(True)
        except Exception as e:
            print(f"下载失败: {e}")
            self.signals.finished.emit(False)

    def hook(self, d):
        if d['status'] == 'downloading':
            speed = d.get('speed', 0)
            percent = d.get('_percent_str', '0.0%').strip()
            try:
                percent = float(percent.strip('%'))
            except:
                percent = 0
            self.signals.progress.emit({
                "speed": speed,
                "percent": percent
            })
